package com.csun.nusing.util;

import android.content.SharedPreferences;
import android.os.Looper;
import android.widget.Toast;

import com.csun.nusing.App;

/**
 * 作者: Created by fzq on 2018/2/2 15:08
 * 邮箱: 15997123593@163.com
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static CrashHandler instance = new CrashHandler();
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    // private Context mContext;
    private App myApp;
    private SharedPreferences sp;

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        if (instance == null)
            instance = new CrashHandler();
        return instance;
    }

    public void setCustomCrashHanler(App myApp) {
        this.myApp = myApp;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        // mContext = context;
        // 崩溃时将catch住异常
        Thread.setDefaultUncaughtExceptionHandler(this);
    }
    /*
     * Crash工具
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        // saveCrash(mContext);
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
//            Intent intent = new Intent(myApp.getApplicationContext(),
//                    StartService.class);
//            myApp.getApplicationContext().stopService(intent);
        }
    }

    /**
     * 错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        // 自定义处理错误信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(myApp.getApplicationContext(),
                        "ui error", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }.start();
        return true;
    }
}